package com.github.gaojh.starter.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;

/**
 * @author gaojh
 * @since 2020/4/14
 */
public class RabbitContext {

    private Connection connection;

    private Map<String, Channel> channelMap = new ConcurrentHashMap<>();

    public RabbitContext(Connection connection) {
        this.connection = connection;
    }

    public void addChannel(String name, Channel channel) {
        if (channelMap.containsKey(name)) {
            Channel existChannel = channelMap.get(name);
            if (existChannel.isOpen()) {
                try {
                    existChannel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                } finally {
                    channelMap.remove(name);
                }
            }

            channelMap.put(name, channel);
        }
    }

    public Channel getChannel(String name) {
        Channel channel = channelMap.get(name);

        if (channel == null) {
            try {
                channel = this.connection.createChannel();
                this.channelMap.put(name, channel);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return channel;
    }

    public List<Channel> getAllChannel(){
        return new ArrayList<>(channelMap.values());
    }

}
